<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import TnNavbar from '@tuniao/tnui-vue3-uniapp/components/navbar/src/navbar.vue'
import TnSubsection from '@tuniao/tnui-vue3-uniapp/components/subsection/src/subsection.vue'
import TnSubsectionItem from '@tuniao/tnui-vue3-uniapp/components/subsection/src/subsection-item.vue'
import TnListItem from '@tuniao/tnui-vue3-uniapp/components/list/src/list-item.vue'
import TnButton from '@tuniao/tnui-vue3-uniapp/components/button/src/button.vue'
import ChatItem from '@/components/chat-item/chat-item.vue'
import CustomPopup from '@/components/CustomPopup/index.vue'
import ChatInputBar from '@/components/chat-input-bar/chat-input-bar.vue'
import TnModal from '@tuniao/tnui-vue3-uniapp/components/modal/src/modal.vue'
import type { TnModalInstance } from '@tuniao/tnui-vue3-uniapp/components/modal'
import type { ChatMessageVo, ChatVo, MessageVo, Result } from '@/types'
import type { ZPagingInstance } from '@/types/z-paging'
import type { ChatInputBarInstance } from '@/types/components'
import { ContentType } from '@/enums/message'
import { useModelStore } from '@/store/model'
import api from '@/api'

const modelStore = useModelStore()
const type = ref(0)
const messageList = ref<ChatMessageVo[]>([])
const currentChatId = ref<number | null>()
const chatList = ref<ChatVo[]>([])
const paging = ref<ZPagingInstance>()
const chatPaging = ref<ZPagingInstance>()
const modalRef = ref<TnModalInstance>()
const inputBarRef = ref<ChatInputBarInstance>()
const isSending = ref(false)
const isCreateChat = ref(false)

const chatListState = ref<{
    show: boolean
    list: ChatVo[]
}>({
    show: false,
    list: []
})

const model = computed(() => {
    return type.value === 0 ? modelStore.textModel : modelStore.imageModel
})

const contentType = computed(() => {
    return type.value === 0 ? ContentType.TEXT : ContentType.IMAGE
})

const chatModelTitle = computed(() => {
    return type.value === 0 ? '文本聊天内容列表' : '图片聊天内容列表'
})

const changeType = async (index: number) => {
    await loadChatList()
    paging.value?.reload()
}

const createChat = () => {
    currentChatId.value = null
    chatListState.value.show = false
    isCreateChat.value = true
    paging.value?.reload()
}

const loadChatList = async () => {
    if (!isCreateChat.value) {
        const res = await api.chat.getChatList(contentType.value)
        if (res.data.length > 0) {
            chatList.value = res.data
            currentChatId.value = res.data[0].id
        } else {
            currentChatId.value = null
            chatList.value = []
        }
    }
}

const loadMessageList = async (pageNo: number, pageSize: number) => {
    if (!currentChatId.value) {
        await loadChatList()
    }
    if (currentChatId.value) {
        const res = await api.chatMessage.getChatMessageList(currentChatId.value, pageNo, pageSize / 2)
        if (res.code === 200) {
            paging.value?.completeByTotal(res.rows.reverse(), res.total * 2)
        }
    } else {
        paging.value?.completeByTotal([], 0)
    }
}

const loadChatPaging = (pageNo: number, pageSize: number) => {
    chatPaging.value?.completeByTotal(chatList.value, chatList.value.length);
}

const changeChat = (item: ChatVo) => {
    currentChatId.value = item.id
    paging.value?.reload()
    chatListState.value.show = false
}

const delChat = (item: ChatVo) => {
    modalRef.value?.showModal({
        title: '操作提示',
        content: '确认要删除该聊天记录吗？',
        showCancel: true,
        cancel: () => {
            console.log('点击了取消按钮')
        },
        confirm: () => {
            api.chat.delChat(item.id!).then(async (res) => {
                if (res.code === 200) {
                    const isReloadPage = item.id === currentChatId.value
                    await loadChatList()
                    chatPaging.value?.reload()
                    if (isReloadPage) {
                        currentChatId.value = null
                        paging.value?.reload()
                    }
                }
            })
        },
    })
}

const doSend = (msg: string) => {
    isSending.value = true
    uni.showLoading({
        title: '发送中...'
    })
    setTimeout(async () => {
        uni.hideLoading();

        if (!currentChatId.value) {
            const res = await api.chat.createChat(msg, contentType.value)
            if (res.code === 200) {
                currentChatId.value = res.data.id
                isCreateChat.value = false
                await loadChatList()
            }
        }

        paging.value?.addChatRecordData([{
            role: 'user',
            content: msg,
            contentType: contentType.value,
        }]);


        let res: Result<MessageVo>
        try {
            if (type.value === 0) {
                res = await api.message.textChat(model.value, currentChatId.value!, msg)
            } else {
                res = await api.message.imageChat(model.value, currentChatId.value!, msg)
            }

            isSending.value = false
            if (res.code === 200) {
                paging.value?.addChatRecordData([{
                    role: 'assistant',
                    content: res.data.assistantMessage.content,
                    contentType: res.data.assistantMessage.contentType,
                    imageList: res.data.assistantMessage.imageList,
                    status: res.data.assistantMessage.status,
                    createTime: res.data.assistantMessage.createTime,
                }]);
                paging.value?.reload()
                inputBarRef.value?.onFocus()
            }
        } catch (e) {
            isSending.value = false
        }
    }, 50)
}

const openChatList = () => {
    chatListState.value.show = true
    chatPaging.value?.reload()
}

onMounted(async () => {
    modelStore.initModel()
})
</script>
<template>

    <view class="tn-flex tn-flex-column tn-w-full">
        <view class="tn-flex tn-flex-column tn-flex-grow">
            <z-paging ref="paging" v-model="messageList" use-chat-record-mode empty-view-text="还没有聊天记录"
                @query="loadMessageList">
                <template #top>
                    <view class="tn-flex tn-flex-row justify-center tn-p-xl tn-pt-sm tn-pb-sm">
                        <TnSubsection @change="changeType" v-model="type">
                            <TnSubsectionItem title="文本" />
                            <TnSubsectionItem title="图片" />
                        </TnSubsection>
                    </view>
                </template>
                <view v-for="(item, index) in messageList" :key="index" style="position: relative;">
                    <view style="transform: scaleY(-1);">
                        <ChatItem :item="item" />
                    </view>
                </view>
                <template #bottom>
                    <view v-if="isSending" class="tn-text-center tn-text-gray-6 tn-p-lg">
                        <kevy-loading :transparent="false" type="nb-spinner" color="blue" tip-color="blue"
                            tip="请求中..."></kevy-loading>
                    </view>

                    <view class="tn-flex tn-flex-row">
                        <chat-input-bar ref="inputBarRef" @send="doSend" @chatClick="openChatList" />
                    </view>
                </template>
            </z-paging>
        </view>

    </view>

    <CustomPopup v-model="chatListState.show" height="80%" :title="chatModelTitle">
        <view class="tn-mt tn-h-full">

            <z-paging ref="chatPaging" v-model="chatListState.list" safe-area-inset-bottom :refresher-enabled="false"
                :loading-more-enabled="false" :default-page-size="100" :fixed="false" @query="loadChatPaging">
                <view class="tn-border-bottom tn-black_border"></view>
                <view class="item" v-for="(item, index) in chatListState.list" :key="index">
                    <view class="tn-border-bottom tn-black_border tn-p-sm"
                        :class="{ 'tn-type-primary_bg': currentChatId === item.id }">
                        <view class="tn-flex tn-flex-row">
                            <view @click="changeChat(item)"
                                class="tn-flex tn-flex-grow tn-flex-column tn-flex-start-center">
                                <view class="tn-text-xl tn-mb-xs">{{ item.title }}</view>
                                <view class="tn-gray-dark_text">{{ item.createTime }}</view>
                            </view>
                            <view class="tn-flex-center-center tn-p">
                                <TnIcon @click="delChat(item)" name="delete" size="44" />
                            </view>
                        </view>
                    </view>
                </view>
            </z-paging>
        </view>
        <template #bottom>
            <view class="tn-mt-lg">
                <TnButton @click="createChat" width="100%" size="xl">新建对话</TnButton>
            </view>
        </template>
    </CustomPopup>

    <TnModal ref="modalRef" :z-index="99999999" />
</template>
<style lang="scss" scoped></style>